layui.use(['table','form', 'element', 'laypage'], function () {
    var element = layui.element, view = layui.view,
        admin = layui.admin, laypage = layui.laypage;

    // 当前所在文件夹
    var nowFolder = {"id": parseInt($('#folderID')[0].innerText), "name": $('#name')[0].innerText};
    var page = 1, limit = 50;

    // 渲染界面
    function renderTable(folder) {
        var load = layer.load(2);
        $.ajax({
            url:  "/f/folder/" + folder['id'] + "?page=" + page + "&limit=" + limit,
            headers:{'Cookie': layui.data('itstudio')['Cookie']},
            dataType: 'JSON',
            complete: function (result) {
                layer.close(load);
                result = result.responseJSON;
                if (result['status'] !== 200) {
                    layer.msg(result['message']);
                    return
                }
                $('#tbody').empty();
                var folders = result['data']['childFolders'];
                var files = result['data']['childFiles'];
                var folderPath = result['data']['path'];
                nowFolder = result['data']['this'];
                renderFolder(folders);
                renderFile(files);
                renderPath(folderPath);
                renderOps();
                renderPage(result['data']['count']);
            }
        })
    }
    // 渲染文件夹
    function renderFolder(folders) {
        var userCode = layui.data('userInfo').userCode;
        for (var i = 0; i < folders.length; i++) {
            var folder = folders[i];
            var ops = "";
            if (folder['userCode'] === userCode) {
                ops = '<button name="folder-' + folder['id'] + '" class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon layui-icon-delete"></i> </button>'
            }
            var tr = $(['<tr>'
                ,'<td style="cursor: pointer;" id="folder-' + folder["id"] + '"><svg class="icon" aria-hidden="true">' +
                '<use xlink:href="#icon-folder"></use>' +
                '</svg><a>&nbsp;&nbsp;'+ $("<div>").text(folder.name).html() +'</a></td>'
                ,'<td></td>'
                ,'<td></td>'
                ,'<td>'
                ,ops
                ,'</td>'
                ,'</tr>'].join(''));
            tr.find(".layui-btn-danger").on("click", function () {
                var folderID = this.name.split('-')[1];
                layer.confirm("确认删除", function (index) {
                    layer.close(index);
                    var load = layer.load(2);
                    $.ajax({
                        url:  "/f/folder/delete/" + folderID,
                        type: 'POST',
                        dateType: 'JSON',
                        complete: function(result) {
                            layer.close(load);
                            result = result.responseJSON;
                            if (result['status'] !== 200) {
                                layer.msg(result['message']);
                                return
                            }else {
                                layer.msg("删除成功");
                                renderTable(nowFolder);
                            }
                        }
                    })
                })
            });
            $('tbody').append(tr);
            var folderID = folder['id'];
            // 点击文件夹
            $('#folder-' + folderID).click(function (event) {
                nowFolder['id'] = event.currentTarget.id.split("-")[1];
                nowFolder['name'] = this.innerText;
                page = 1;
                renderTable(nowFolder);
            });
        }
    }
    // 渲染文件
    function renderFile(files) {
        var userCode = layui.data('userInfo').userCode;
        for (var i = 0; i < files.length; i++) {
            var file = files[i];
            var myOps = "";
            if (file['userCode'] === userCode) {
                myOps = '<button name="delete-' + file['shareID'] + '" class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon layui-icon-delete"></i></button>'
            }
            var tr = $(['<tr>'
                , '<td style="cursor: pointer;" ><a href="/f/' + file["shareID"]  + '"><svg class="icon" aria-hidden="true">' +
                '  <use xlink:href="#' + getFileIcon(file['name']) +'"></use>' +
                '</svg>&nbsp;&nbsp;' + $("<div>").text(file['name']).html() + '</a></td>'
                , '<td>' + getFileSize(file['size']) + '</td>'
                , '<td>' + timestampToTime(file['uploadTime']) + '</td>'
                , '<td>'
                , '<button name="preview-' + file['shareID'] + '"  class="layui-btn layui-btn-xs layui-btn-primary" ><svg class="icon" aria-hidden="true">' +
                '<use xlink:href="#icon-preview"></use>' +
                '</svg></button>'
                , '<button name="share-' + file['shareID'] + '"  class="layui-btn layui-btn-xs layui-btn-normal" ><i class="layui-icon layui-icon-share"></i></button>'
                , myOps
                , '</td>'
                , '</tr>'].join(''));

            // 共享链接
            tr.find(".layui-btn-normal").on('click', function () {
                var shareID = this.name.split("-")[1];
                admin.popup({
                    title: "共享链接",
                    area: ["420px", "520px"],
                    id: "Share-Form",
                    success: function (layero, index) {
                        view(this.id).render("menu/resource/share").done(function () {
                            var shareURL = "https://itstudio.club/f/" + shareID;
                            $('#share-url')[0].innerText = shareURL;
                            jQuery('#share-qrcode').qrcode(shareURL);
                        })
                    }
                })
            });

            // 预览
            tr.find(".layui-btn-primary").on('click', function () {
                var str = this.name.split("-");
                var shareID = str[1];
                var load = layer.load(2);
                $.ajax({
                    url:  "/f/preview/" + shareID,
                    dataType: 'JSON',
                    complete: function (result) {
                        layer.close(load);
                        result = result.responseJSON;
                        if (result['status'] === 200) {
                            setTimeout(function () {
                                window.open(result['data'])
                            }, 0);
                        }else {
                            layer.msg("预览链接加载失败，建议点击重试！")
                        }
                    }
                });
            });
            tr.find(".layui-btn-danger").on("click", function () {
                var shareID = this.name.split("-")[1];
                layer.confirm("确认删除", function (index) {
                    layer.close(index);
                    var load = layer.load(2);
                    $.ajax({
                        url:  "/f/delete/" + shareID,
                        type: 'POST',
                        dataType: 'JSON',
                        complete: function (result) {
                            layer.close(load);
                            result = result.responseJSON;
                            if (result['status'] !== 200) {
                                layer.msg(result['message']);
                                return
                            }else {
                                layer.msg("删除成功");
                                renderTable(nowFolder);
                            }
                        }
                    })
                });
            });
            $('tbody').append(tr)
        }
    }
    // 渲染路径
    function renderPath(folderPath) {
        $('#folder-path').empty();
        if(folderPath.length === 0) {
            var a = $("<a style='cursor: pointer'><cite>" + $('#name')[0].innerText + "</cite></a>");
            $('#folder-path').append(a);
        }else {
            for (var i = 0; i < folderPath.length; i++) {
                var folder = folderPath[i];
                var a = $("<a style='cursor: pointer' id='path-" + folder["id"] + "'><cite>" + folder["name"] + "</cite></a>");
                $('#folder-path').append(a);
                $('#path-' + folder["id"]).click(function (event) {
                    nowFolder['id'] = event.currentTarget.id.split("-")[1];
                    nowFolder['name'] = this.innerText;
                    page = 1;
                    renderTable(nowFolder);
                });
                // 分割线
                $('#folder-path').append($('<span lay-separator="">/</span>'));
            }
            var a = $("<a style='cursor: pointer'><cite>" + nowFolder['name'] + "</cite></a>");
            $('#folder-path').append(a);
        }
    }

    function renderOps() {
        $('#create').addClass("layui-hide");
        $('#upload').addClass("layui-hide");
        var userInfo = layui.data("userInfo");
        var userCode = userInfo.userCode;
        if (nowFolder['userCode'] === "") {
            $('#create').removeClass("layui-hide")
        }else if (userCode === nowFolder['userCode']) {
            $('#create').removeClass("layui-hide");
            $('#upload').removeClass("layui-hide")
        }else {

        }
    }

    function getFileIcon(fileName) {
        var fileSp = fileName.split(".");
        var suffix = fileSp[fileSp.length - 1];
        switch (suffix) {
            case "pdf":
                return "icon-pdf";
            case "mp3":
                return "icon-mp";
            case "doc":
            case "docx":
                return "icon-Microsoft-Word";
            case "xls":
            case "xlsx":
                return "icon-Microsoft-Excel";
            case "ppt":
            case "pptx":
                return "icon-Microsoft-Powerpoint";
            case "tar":
                return "icon-tar";
            case "txt":
                return "icon-TXT";
            case "zip":
                return "icon-zip";
            default:
                return "icon-file";
        }
    }

    // 把文件大小变为可读的形式
    function getFileSize(size) {
        size /= 1000;
        if (size > 1000) {
            size /= 1000;
            return size.toFixed(1) + "M"
        }
        return size.toFixed(1) + "K"
    }
    // 时间戳变为可读形式
    function timestampToTime(timestamp) {
        var date = new Date(timestamp);
        Y = date.getFullYear() + '-';
        M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        D = change(date.getDate()) + ' ';
        h = change(date.getHours()) + ':';
        m = change(date.getMinutes());
        return Y + M + D + h + m;
    }
    function change(t) {
        if (t < 10) {
            return "0" + t;
        } else {
            return t;
        }
    }

    // 获取文件后缀名
    function getSuffix(name) {
        var str = name.split(".");
        return str[str.length - 1];
    }

    // 监听点击创建文件夹按钮
    $('#create').click(function (event) {
        layer.prompt({
                title: '取个名字吧'
            }, function (value, index, elem) {
                value = value.trim();
                var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]");
                if(pattern.test(value)){
                    layer.msg("特殊字符", {icon: 5});
                    return;
                }
                if (value.length > 50) {
                    layer.msg("文件夹名字太长了");
                    return;
                }
                var load = layer.load(2);
                var data = {
                    'name':value,
                    'parentID': nowFolder["id"]
                };
                $.ajax({
                    url:  '/f/folder/create',
                    dataType: 'json',
                    data: data,
                    type: 'POST',
                    complete: function (result) {
                        layer.close(index);
                        layer.close(load);
                        var code = result.responseJSON.status;
                        var message = result.responseJSON.message;
                        if (code === 200) {
                            layer.msg("创建成功", {
                                time: 1000
                            }, function () {
                                renderTable(nowFolder);
                            })
                        }else {
                            layer.msg(message);
                        }
                    }
                })
            }
        )
    });

    // 渲染分页
    function renderPage(count) {
        // 先隐藏
        $('#lay-page').hide();
        // 一页放不下，我要开启分页了
        if (count > limit) {
            $('#lay-page').show();
            laypage.render({
                elem: 'lay-page'
                ,count: count
                ,curr: page
                ,limit: limit
                ,jump: function (obj, first) {
                    if (!first) {
                        page = obj.curr;
                        renderTable(nowFolder);
                    }
                }
            });
        }
    }

    // 监听上传按钮
    $('#upload').click(function () {
        layer.msg("请使用客户端上传,下载链接在右上方！")
    });

    renderTable(nowFolder);
});